import {useRequest} from "ahooks";
import {useSearchParams} from "react-router-dom";
import {useEffect, useState} from "react";
import useGetUserInfo from "./useGetUserInfo";
import {getUserInfoService} from "../services/user";
import {useDispatch} from "react-redux";
import {loginReducer} from "../store/userRreducer";

function useLoadUserDate() {
    const dispatch = useDispatch()

    const [waitingUserData, setWaitingUserData] = useState(true);

    //ajax 加载
    const {run} = useRequest(getUserInfoService, {
        manual: true,
        onSuccess: (result) => {
            const {username, nickname} = result
            dispatch(loginReducer({username, nickname}))
        }, onFinally: () => {
            setWaitingUserData(false)
        }
    })

    //判断当前redux store 是否已经存在用户信息
    const {username} = useGetUserInfo()
    useEffect(() => {
        if (username) {
            setWaitingUserData(false)
            return
        }
        run()
    }, [username])

    return {waitingUserData}
}

export default useLoadUserDate;